﻿using AutoCommunication.Base;
using AutoCommunication.Clients;
using AutoCommunication.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using AutoCommunication.Enums;
using System.Collections.ObjectModel;

#if NET461_OR_GREATER || NET5_0_OR_GREATER

using System.Windows.Forms;

namespace AutoCommunication
{
    public partial class Form_Configure : Form
    {
        public Form_Configure()
        {
            InitializeComponent();
            // this.Width = 1250; this.Height = 750;
            var sourse = typeof(IDevice).Assembly.GetTypes().Where(x => x.GetInterfaces().Contains(typeof(IDevice)) && !x.IsAbstract).ToList();

            comboBox_AllDeviceType.DisplayMember = "Name";
            comboBox_AllDeviceType.DataSource = sourse;

            propertyGrid1.SelectedGridItemChanged += PropertyGrid1_SelectedGridItemChanged;
        }

        private void PropertyGrid1_SelectedGridItemChanged(object sender, SelectedGridItemChangedEventArgs e)
        {
            int a = listBox_Devs.SelectedIndex;
            listBox_Devs.DataSource = null;
            listBox_Devs.DataSource = devlist;
            listBox_Devs.DisplayMember = "Name";
            listBox_Devs.SelectedIndex = a;
        }

        private void CheckDevlistIsRepeat()
        {
            var group = devlist.GroupBy(x => x.Name.Norm());
            foreach (var item in group)
            {
                if (item.Count() > 1)
                {
                    MessageBox.Show(item.Key + ":这个设备名重复");
                }
            }
        }

        private ObservableCollection<IDevice> devlist = new();

        private IDevice CreateDevic(Type type)//CreateDevic By Type
        {
            IDevice dev = null;
            if (type == typeof(DevSiemens))
            {
                dev = new DevSiemens()
                {
                    AllVarable = new List<VarableSiemens>()
                    {
                        new VarableSiemens("mb0",DataTypeEnum.Byte) { Name = "mb0", DataChangeEnable = false },
                        new VarableSiemens("mb3.5", DataTypeEnum.Bool) { Name = "mb3.5" ,DataChangeEnable=true},
                        new VarableSiemens("db3.dbw2", DataTypeEnum.UInt16){ Name ="int"},
                        new VarableSiemens("md23", DataTypeEnum.Float),
                       new VarableSiemens("db3.dbw14", DataTypeEnum.String){ Name ="string",Bytelength=20},
                        new VarableSiemens("db3.dbw270", DataTypeEnum.Wstring){ Name ="wstring",Bytelength=500},
                    },
                };
            }
            else if (type == typeof(DevModbusRtu))
            {
                dev = new DevModbusRtu()
                {
                    AllVarable = new List<VarableModbus>()
                   {
                  new VarableModbus("00001", DataTypeEnum.Bool){ Name="00001"},
                  new VarableModbus("00002", DataTypeEnum.Bool){ Name="00002"},
                   new VarableModbus("40001", DataTypeEnum.Int16){ Name="40001"},
                 //  new VarableModbus("50001", DataTypeEnum.Int16){ Name="400033"},//错误的地址
                  new VarableModbus("40004", DataTypeEnum.Float){ Name="40004"}
                   }
                };
            }
            else if (type == typeof(DevModbusTcp))
            {
                dev = new DevModbusTcp()
                {
                    AllVarable = new List<VarableModbus>()
                   {
                   new VarableModbus("00001", DataTypeEnum.Bool){ Name="00001"},
                   new VarableModbus("00002", DataTypeEnum.Bool){ Name="00002"},
                   new VarableModbus("40001", DataTypeEnum.Int16){ Name="40001"},
                 //  new VarableModbus("50001", DataTypeEnum.Int16){ Name="400033"},
                  new VarableModbus("40004", DataTypeEnum.Float){ Name="40004"}
                   }
                };
            }
            else if (type == typeof(DevMitsubishi))
            {
                //  dev = new MitsubishiClient();
            }
            else
            {
                MessageBox.Show("类型不对");
            }
            return dev;
        }

        private void button1_Click(object sender, EventArgs e)//Show Device By Winfom
        {
            if (listBox_Devs.SelectedItem != null)
            {
                ((IDevice)listBox_Devs.SelectedItem).ShowByWinform();
            }
            else
            {
                MessageBox.Show("请新建或者选择一个要测试的设备");
            }
        }

        private void button2_Click(object sender, EventArgs e)//Save Setting
        {
            var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\setting.json";

            devlist.SaveAsJson(path).ShowMessageBox("\r\n默认保存在桌面，文件名称“setting.json”");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show(this.Width.ToString());
        }

        private void button4_Click(object sender, EventArgs e)//Load Setting
        {
            OpenFileDialog o = new OpenFileDialog();
            o.Filter = "setting.json|*.Json|all|*.*";
            if (o.ShowDialog() == DialogResult.OK)
            {
                var res = Auto.LoadByJson(o.FileName);

                if (res.IsSucceed)
                {
                    devlist = res.Value;
                    listBox_Devs.DataSource = devlist;
                    listBox_Devs.DisplayMember = "Name";
                }
                else
                {
                    res.ShowMessageBox();
                }
            }
        }

        private void button5_Click(object sender, EventArgs e)//Add Device
        {
            var dev = CreateDevic(comboBox_AllDeviceType.SelectedItem as Type);
            if (dev == null)
            {
                MessageBox.Show("这个设备还没实现哦,请期待..");
                return;
            }
            if (dev == null)
            {
                MessageBox.Show("大哥,请先选择一个要添加的设备");
                return;
            }
            int c = 0;
            var name = dev.Name.Norm() + c;
            while (!(devlist.FirstOrDefault(x => x.Name.Norm() == name.Norm()) == null))
            {
                c++;
                name = dev.Name + c;
            }
            dev.Name = name.Norm();
            var res = dev.Init1();
            if (res.IsSucceed)
            {
                devlist.Add(dev);
                propertyGrid1.SelectedObject = devlist.Last();
                listBox_Devs.DataSource = null;
                listBox_Devs.DataSource = devlist;
                listBox_Devs.DisplayMember = "Name";
                listBox_Devs.SelectedItem = devlist.Last();
            }
            else
            {
                res.ShowMessageBox();
            }
        }

        private void button6_Click(object sender, EventArgs e)//Delete Device
        {
            var x = devlist.Remove((listBox_Devs.SelectedItem as IDevice));
            listBox_Devs.DataSource = null;
            listBox_Devs.DataSource = devlist;
            if (devlist.Any())
            {
                listBox_Devs.SelectedItem = devlist.Last();
                listBox_Devs.DisplayMember = "Name";
            }
        }

        private void listBox_Devs_Click(object sender, EventArgs e)//Select Device
        {
            //用SelectChange事件触发好像有Bug,改用Click事件
            if (listBox_Devs.SelectedItem != null)
            {
                propertyGrid1.SelectedObject = listBox_Devs.SelectedItem;
            }
            CheckDevlistIsRepeat();
        }
    }
}

#endif